package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    private final ISeckillVoucherService seckillVoucherService;
    private final RedisIdWorker redisIdWorker;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;
    private final RabbitTemplate rabbitTemplate;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );
        int code = result.intValue();
        if(code!=0){
            return Result.fail(code==1?"库存不足":"不能重复下单");
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        long  orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //使用rabbitmq实现异步扣减库存和更新库存状态
        rabbitTemplate.convertAndSend("seckill.order.exchange","seckill.order",voucherOrder);
        return Result.ok(orderId);
    }
   /* @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {

        //1. 查询优惠卷
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //2.判断是否开始
        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        //3.判断是否结束
        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        //4.判断库存是否充足
        if(seckillVoucher.getStock()<1){
            return Result.fail("库存不足");
        }
        */



    /**
         * 当高并发场景时，很多线程会同时判断用户与订单号的存在与否，当多个线程第一次以同一个用户访问数据库时，
         * 这时不加锁值判断count > 0是不行的，
         * 斌且加锁的话，必须以每个用户的id为锁，这样才能保证每个用户只能购买一次，
         * 并且该锁得加在@Transactional注解之上，否则会出现线程不安全问题。
         * *//*
        Long userId = UserHolder.getUser().getId();
        //创建锁对象
        //SimpleRedisLock lock = new SimpleRedisLock(userId.toString(), stringRedisTemplate);
        RLock lock = redissonClient.getLock(userId.toString());
        //获取锁
        boolean isLock = lock.tryLock();
        //判断获取锁是否成功
        if(!isLock){
            //获取锁失败，直接返回失败或者重试
            return Result.fail("不允许重复下单");
        }
        try {
            //获取事务代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }*/
    @Transactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "seckill.order.queue",durable = "true"),
            exchange = @Exchange(value = "seckill.order.exchange"),
            key = {"seckill.order"}
    ))
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //5.实现一人一单逻辑
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Long count = lambdaQuery().eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherId)
                .count();
        if(count>0){
          log.error("用户已经购买过一次了");
          throw new IllegalArgumentException("用户已经购买过一次了");
        }

        //5.扣减库存
        boolean update = seckillVoucherService.update()
                .setSql("stock = stock - 1")//set stock = stock - 1
                .eq("voucher_id", voucherId) //where voucher_id = ?
                .gt("stock",0) //where stock > 0 乐观锁
                .update();
        if(!update){
           throw new IllegalArgumentException("库存不足");
        }
        //6.创建订单
        save(voucherOrder);
    }
}
